package com.acme.bankapp.domain.bank;

import java.io.Serializable;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;

import com.acme.bankapp.domain.bank.exceptions.ClientAlreadyExistsException;

public class Bank implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private List<Client> clients = new ArrayList<Client>();

	public interface ClientRegistrationListener {
		void onClientAdded(Client client);
	}

	transient private List<ClientRegistrationListener> clientRegistrationListeners = new ArrayList<ClientRegistrationListener>();

	public Bank() {
		this.addClientRegistrationListener(new Bank.ClientRegistrationListener() {
					public void onClientAdded(Client client) {
						System.out.println("Client " + client.getClientSalutation() + " added");
					}
				}
			);

		this.addClientRegistrationListener(new Bank.ClientRegistrationListener() {
					public void onClientAdded(Client client) {
						System.out.println("Notification email about the new client " + client.getClientSalutation() + " to be sent");
					}
				}
			);

	}
	
	public Bank(final List<ClientRegistrationListener> listeners){
		this.clientRegistrationListeners.addAll(listeners);
	}

	public Client addClient(final Client client) throws ClientAlreadyExistsException{
		for (Client cl: this.clients){
			if (cl.equals(client)){
				throw new ClientAlreadyExistsException();
			}
		}
		clients.add(client);
		for (ClientRegistrationListener clRegListener : clientRegistrationListeners){
			clRegListener.onClientAdded(client);
		}
		return client;
	}

	public List<Client> getClients() {
		return Collections.unmodifiableList(clients);
	}

	public List<Account> getClientAccounts(int clientNumber) {
		if (this.clients.get(clientNumber) != null) {
			return this.clients.get(clientNumber).getAccounts();
		} else {
			return null;
		}
	}

	public List<Account> getAllAccounts() {
		List<Account> allAccounts = new ArrayList<Account>();

		for (Client cl : clients) {
			allAccounts.addAll(cl.getAccounts());
		}

		return allAccounts;
	}
	
	public void addClientRegistrationListener(ClientRegistrationListener listener) {
		clientRegistrationListeners.add(listener);
	}


}
